import asyncio
import contextvars

# declare context var
import random

request_id = contextvars.ContextVar('Id of request.')


async def some_inner_coroutine(req_id):
    # get value
    await asyncio.sleep(random.uniform(0, 1))
    print('Processed inner coroutine of request[req_id]: {} - {}'.format(req_id, request_id.get()))
    request_id.set(req_id + 100)
    async def inner_task(r_id):
        print('------------> bb', asyncio.current_task())
        await asyncio.sleep(random.uniform(0, 1))
        print('inner_task r_id: {} - {}'.format(r_id, request_id.get()))

    await asyncio.create_task(inner_task(req_id))
    print('------------>', asyncio.current_task())


async def some_outer_coroutine(req_id):
    # set value
    request_id.set(req_id)
    print('------------> aa', asyncio.current_task())

    await some_inner_coroutine(req_id)

    # get value
    print('Processed outer coroutine of request: {}'.format(request_id.get()))


async def main():
    tasks = []
    for req_id in range(1, 5):
        tasks.append(asyncio.create_task(some_outer_coroutine(req_id)))

    await asyncio.gather(*tasks)


if __name__ == '__main__':
    asyncio.run(main())